package com.alks.function.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alks.common.config.handler.AutoCellWriteWidthHandle;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.PcLotExp2;
import com.alks.entity.data.enums.chengkong.DefineEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.PcLotExp2Dto;
import com.alks.function.data.dto.PcLotUsageChgDto;
import com.alks.function.data.dto.PcLotUsageFitChgDto;
import com.alks.function.data.request.PcLotExp2Request;
import com.alks.function.mapper.PcLotExp2Mapper;
import com.alks.function.service.PcLotExp2Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PcLotExp2ServiceImpl implements PcLotExp2Service {

    @Resource
    private PcLotExp2Mapper pcLotExp2Mapper;

    /**
     * 选择版本
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getVersions(PcLotExp2Request request) {

        Map map=new HashMap();

        //设置分页参数
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());

        request.setCompanyId(UserIdThread.get().getCompanyId());
        //选择版本
        List<PcLotExp2Dto> selectVersion = pcLotExp2Mapper.getSelectVersion(request);

        //拿到total
        PageInfo list=new PageInfo(selectVersion);

        map.put("selectVersion",selectVersion);
        map.put("total",list.getTotal());

        return ResponseInfo.ok(map);
    }

    /**
     * 指令用量差异
     * @param lotNo
     * @param version
     * @return
     */
    @Override
    public ResponseInfo getInstructUsageDifference(String lotNo, Integer version) {

        //查询指令用量差异
        List<PcLotUsageChgDto> usageDifference = pcLotExp2Mapper.getUsageDifference(lotNo, version,UserIdThread.get().getCompanyId());
        for (PcLotUsageChgDto pcLotUsageChgDto : usageDifference) {

            //判断备注是否为空
            if (StringUtils.isNotEmpty(pcLotUsageChgDto.getRemark())){
                pcLotUsageChgDto.setCfmFlag("Y");
            }
        }

        return ResponseInfo.ok(usageDifference);
    }

    /**
     * 子材料用量差异
     *
     * @param mtlNo
     * @param version
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo getWheelMaterialUsageDifference(String mtlNo, Integer version, Integer seqNo, String lotNo) {

        //子材料用量差异
        List<PcLotUsageFitChgDto> wheelMaterialUsageVariance = pcLotExp2Mapper.getWheelMaterialUsageVariance(mtlNo, version, seqNo,UserIdThread.get().getCompanyId(),lotNo);

        return ResponseInfo.ok(wheelMaterialUsageVariance);
    }

    /**
     * 指令用量差异计算返回型体颜色
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo getStyle2Color(String lotNo) {
        return ResponseInfo.ok(pcLotExp2Mapper.getStyle2Color(lotNo,UserIdThread.get().getCompanyId()));
    }

    /**
     * 指令用量差异计算返回条件
     * @return
     */
    @Override
    public ResponseInfo getConditionBox() {
        Map map =new HashMap();

        String companyId = UserIdThread.get().getCompanyId();
        List<String> remark = pcLotExp2Mapper.getRemark(companyId);
        List<String> style = pcLotExp2Mapper.getStyle(companyId);

        map.put("remark",remark);
        map.put("style",style);

        return ResponseInfo.ok(map);
    }

    /**
     * 写入日志
     * @param lotNo
     * @param reason
     * @param companyId
     * @param userName
     * @param flag
     * @param version
     */
    public void addPcLotExp2(String lotNo, String reason, String companyId, String userName,String flag,Integer version) {
        PcLotExp2 pcLotExp2 = new PcLotExp2();
        pcLotExp2.setSeqNo(BigDecimal.valueOf(version+1));
        pcLotExp2.setLotNo(lotNo);
        pcLotExp2.setCompanyId(companyId);
        pcLotExp2.setExportFlag(DefineEnum.CHECKOUT_FLAG.getValue());
        pcLotExp2.setSeqNo(BigDecimal.valueOf(version+1));
        pcLotExp2.setUpdateUser(userName);
        pcLotExp2.setUpdateTime(LocalDateTime.now());
        pcLotExp2.setRemark(reason);
        pcLotExp2.setPurHideFlag(flag);
        pcLotExp2Mapper.addPcLotExp2(pcLotExp2);
    }

    /**
     * 导出明细
     * @param lotNo
     * @param version
     * @param response
     */
    @Override
    public void exportChange(String lotNo, Integer version, HttpServletResponse response) {
        List<PcLotUsageChgDto> list = pcLotExp2Mapper.getUsageDifference(lotNo, version,UserIdThread.get().getCompanyId());
        for (PcLotUsageChgDto t : list) {
            if ("Y".equals(t.getBackgroundColor())){
                t.setBackgroundColor("已转");
            }
        }
        List<PcLotExp2Dto>  selectVersionList = pcLotExp2Mapper.getSelectVersionList(lotNo);
        String fileName = "用量汇总差异明细表" + DateUtils.dateTimeNow() + ".xls";
        try (
                InputStream inputStream = new ClassPathResource("templates/用量汇总差异明细模板.xls").getInputStream();
                OutputStream outputStream = response.getOutputStream();
                ExcelWriter excelWriter = EasyExcel.write(outputStream).excelType(ExcelTypeEnum.XLS).withTemplate(inputStream).registerWriteHandler(new AutoCellWriteWidthHandle()).build();
        ) {
            ExcelUtils.setResponseZF(response, fileName);
            WriteSheet sheet1 = EasyExcel.writerSheet("Sheet1").build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(new FillWrapper("t", list), fillConfig, sheet1);

            WriteSheet sheet2 = EasyExcel.writerSheet("Sheet2").build();
            excelWriter.fill(new FillWrapper("t2", selectVersionList), fillConfig, sheet2);
            excelWriter.finish();
        } catch (Exception e) {
            log.error("用量汇总差异明细表导出失败, 错误信息: {}", e.getMessage(), e);
            throw new ServiceErrorException("用量汇总差异明细表导出失败!");
        }
    }
}
